<template>
  <!-- 数据管理区 -->
  <section class="content-wrapper">

    <!-- 搜索区域 -->
    <div class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="教室名称">
          <el-input
              v-model="searchForm.name"
              placeholder="请输入教室名称"
              class="search-input"
              clearable
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 100px"
          >
            <el-option label="全部" value=""/>
            <el-option label="启用" value="1"/>
            <el-option label="禁用" value="0"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
              type="primary"
              @click="search()"
              :icon="Search"
          >
            查询
          </el-button>
          <el-button
              @click="reset"
              :icon="RefreshLeft"
              class="reset-btn"
          >
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="page-header">
      <el-button
          type="primary"
          @click="add"
          class="add-btn"
          :icon="Plus"
      >
        新增教室
      </el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-card">
      <div class="table-actions">
        <el-button
            type="danger"
            @click="remove"
            :disabled="multipleSelection.length === 0"
            :icon="Delete"
            class="batch-delete-btn"
        >
          批量删除
        </el-button>
      </div>

      <el-table
          :data="tableData"
          border
          class="main-table"
          @selection-change="handleSelectionChange"
          v-loading="loading"
          element-loading-text="加载中..."
          element-loading-spinner="el-icon-loading"
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="id" label="ID" width="80"/>
        <el-table-column prop="name" label="教室名称" min-width="150">
          <template #default="scope">
            <div class="cell-content">{{ scope.row.name }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="capacity" label="容量" width="100"/>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="scope">
            <el-tag
                :type="scope.row.status === 1 ? 'success' : 'danger'"
                class="status-tag"
            >
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150">
          <template #default="scope">
            <div class="cell-content">{{ scope.row.remark }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button
                  type="text"
                  @click="edit(scope.row)"
                  class="edit-btn"
              >
                <i class="el-icon-edit"/> 编辑
              </el-button>
              <el-button
                  type="text"
                  @click="removeRow(scope.row.id)"
                  class="delete-btn"
              >
                <i class="el-icon-delete"/> 删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="roomPi.pageNo"
            v-model:page-size="roomPi.pageSize"
            layout="total, prev, pager, next, jumper"
            :total="roomPi.total"
            @change="roomPiChange"
        />
      </div>
    </div>
  </section>
  <!-- 新增/编辑弹窗 -->
  <el-dialog
      v-model="dialogVisible"
      :title="form.id ? '编辑教室' : '新增教室'"
      width="600px"
      :before-close="handleDialogClose"
      :transition="dialogTransition"
  >
    <el-form
        :model="form"
        label-width="120px"
        :rules="formRules"
        ref="formRef"
        class="dialog-form"
    >
      <el-form-item label="教室名称" prop="name">
        <el-input
            v-model="form.name"
            placeholder="请输入教室名称"
            maxlength="50"
        />
      </el-form-item>
      <el-form-item label="容量" prop="capacity">
        <el-input
            v-model.number="form.capacity"
            type="number"
            placeholder="请输入容量"
            min="1"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="form.status" placeholder="请选择状态">
          <el-option label="启用" value="1"/>
          <el-option label="禁用" value="0"/>
        </el-select>
      </el-form-item>
      <el-form-item label="备注">
        <div style="display: flex; gap: 8px; width: 100%;">
          <el-input
              v-model="form.remark"
              placeholder="请输入备注信息"
              type="textarea"
              rows="3"
              maxlength="200"
              style="flex: 1;"
          />
          <!-- AI按钮 -->
          <el-button
              type="primary"
              @click="generateRemark"
              :loading="aiLoading"
              style="height: 40px; align-self: flex-start;"
          >
            AI生成
          </el-button>
        </div>
      </el-form-item>

    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确认</el-button>
        </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {ref, reactive, onMounted, nextTick, toRaw} from 'vue'
import {
  Plus,
  Search,
  RefreshLeft,
  Delete
} from '@element-plus/icons-vue'
import {ElMessageBox, ElMessage, ElForm} from 'element-plus'
import api from "@/util/api.js"

// 状态管理
let loading = ref(false)
let dialogVisible = ref(false)
let dialogTransition = ref('el-fade-in')
let formRef = ref(null)
let multipleSelection = ref([])

let roomPi = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0
})

// 修复：将 tableData 初始化为数组
let tableData = ref([])

// 搜索表单
let searchForm = ref({
  name: '',
  status: '',
})

// 新增表单数据
let form = ref({
  id: '',
  name: '',
  capacity: '',
  status: '1',
  remark: ''
})

// 表单验证规则
const formRules = reactive({
  name: [
    {required: true, message: '请输入教室名称', trigger: 'blur'}
  ],
  capacity: [
    {required: true, message: '请输入容量', trigger: 'blur'},
    {type:'number', message: '容量必须为数字', trigger: 'blur'}
  ],
  location: [
    {required: true, message: '请输入教室位置', trigger: 'blur'}
  ],
  status: [
    {required: true, message: '请选择状态', trigger: 'change'}
  ]
})
let aiLoading = ref(false)

// AI生成备注
async function generateRemark() {
  try {
    aiLoading.value = true


    // 使用用户在备注栏输入的关键词，如果没有则使用默认关键词
    let keywords = form.value.remark || `${form.value.name || '教室'}，容量${form.value.capacity || '未知'}人，状态${form.value.status === '1' ? '启用' : '禁用'}`
    let resp = await api({
      url: "/ai/generateRemark",  // 后端新接口
      method: "post",
      data: { keywords }
    })

    if (resp.success) {
      form.value.remark = resp.data  // 填充AI生成的备注
      ElMessage.success("AI备注生成成功")
    } else {
      ElMessage.error(resp.msg || "AI生成失败")
    }
  } catch (e) {
    ElMessage.error("调用AI接口失败")
  } finally {
    aiLoading.value = false
  }
}


// 初始化加载数据
onMounted(() => {
  search();
})

// 搜索
async function search(pageNo = 1, pageSize = 10) {
  let params = toRaw(searchForm.value);
  let resp = await api({
    url: "/classroom",
    method: "get",
    params: {
      pageNo,
      pageSize,
      ...params,
    }
  });
  tableData.value = resp.data.records;
  roomPi.total = resp.data.total;
  roomPi.pageNo = pageNo;
  roomPi.pageSize = pageSize;
}

// 分页处理
function roomPiChange(pageNo, pageSize) {
  search(pageNo, pageSize)
}

// 重置搜索
function reset() {
  searchForm.value = {
    name: '',
    status: '',
  }
  search();
}

let model = "add";

// 新增
function add() {
  // 重置表单
  if (formRef.value) {
    formRef.value.resetFields()
  }
  // 重置表单数据
  form.id = ''
  form.name = ''
  form.capacity = ''
  form.status = '1'
  form.value.remark = ''

  // 显示弹窗
  dialogVisible.value = true
  model = "add"
}

// 编辑
function edit(row) {
  // 重置表单验证
  if (formRef.value) {
    formRef.value.clearValidate()
  }

  // 填充表单数据
  form.value.id = row.id
  form.value.name = row.name
  form.value.capacity = row.capacity
  form.value.status = row.status.toString() // 确保类型一致
  form.value.remark = row.remark

  // 显示弹窗
  dialogVisible.value = true
  model = "edit"
}

// 保存
function handleSave() {
  if (formRef.value) {
    formRef.value.validate(async (valid) => {
      if (valid) {
        if (model === "add") {
          await submitAdd()
        } else {
          await submitEdit()
        }
      } else {
        ElMessage.error("请填写必填项")
      }
    })
  }
}

async function submitAdd() {
  try {
    let params = toRaw(form.value);
    let resp = await api({
      url: "/classroom",
      method: "post",
      data: params
    });
    if (resp.success) {
      dialogVisible.value = false;
      search();
      ElMessage.success("新增成功")
    } else {
      ElMessage.error(resp.msg || "新增失败")
    }
  } catch (error) {
    ElMessage.error(error.msg || "新增失败")
  }
}

async function submitEdit() {
  try {
    let params = toRaw(form.value);
    let resp = await api({
      url: "/classroom",
      method: "put",
      data: params
    });
    if (resp.success) {
      dialogVisible.value = false;
      search();
      ElMessage.success("修改成功")
    } else {
      ElMessage.error(resp.msg || "修改失败")
    }
  } catch (error) {
    ElMessage.error(error.msg || "修改失败")
  }
}

// 删除
function removeRow(id) {
  ElMessageBox.confirm(
      '此操作将永久删除该教室信息，是否继续？',
      '删除确认',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }
  ).then(() => {
    removeByIds([id]);
  }).catch(() => {
    // 取消删除
    ElMessage({
      type: 'info',
      message: '已取消删除',
    })
  })
}

// 批量删除
function remove() {
  let rows = multipleSelection.value
  ElMessageBox.confirm(
      `此操作将永久删除选中的${multipleSelection.value.length}条教室信息，是否继续？`,
      '批量删除确认',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }
  ).then(() => {
    let ids = rows.map(row => row.id)
    removeByIds(ids);
  }).catch(() => {
    // 取消删除
    ElMessage({
      type: 'info',
      message: '已取消删除',
    })
  })
}

//提交删除
async function removeByIds(ids) {
  let resp = await api({
    url: "/classroom",
    method: "delete",
    data: ids
  });
  if (resp.success) {
    ElMessage.success("删除成功,共删除" + resp.data + "条数据")
    search();
  } else {
    ElMessage({
      type: 'info',
      message: '删除失败',
    })
  }
}

// 处理选择变化
function handleSelectionChange(val) {
  multipleSelection.value = val
}

// 关闭弹窗
function handleDialogClose() {
  dialogVisible.value = false
  // 重置表单验证
  nextTick(() => {
    if (formRef.value) {
      formRef.value.clearValidate()
    }
  })
}
</script>


<style scoped>
.app-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f7fa;
  color: #333;
}

/* 主内容区 */
.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

/* 侧边栏 */
.sidebar {
  width: 220px;
  background-color: #34495e;
  color: #ecf0f1;
  height: calc(100vh - 60px);
  transition: all 0.3s ease;
}

.sidebar-nav {
  padding-top: 20px;
}

.nav-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 12px 20px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.nav-item:hover {
  background-color: #2c3e50;
}

.nav-item.active {
  background-color: #42b983;
  border-left: 4px solid #27ae60;
}

.nav-item .el-icon {
  font-size: 1.1rem;
  width: 20px;
  text-align: center;
}

/* 内容区域 */
.content-wrapper {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

/* 页面标题 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 1.5rem;
  font-weight: 600;
  color: #2c3e50;
  margin: 0;
}

.add-btn {
  background-color: #42b983;
  border-color: #42b983;
  transition: all 0.2s ease;
}

.add-btn:hover {
  background-color: #2ecc71;
  border-color: #2ecc71;
  transform: translateY(-2px);
}

/* 搜索卡片 */
.search-card {
  background-color: white;
  border-radius: 8px;
  padding: 15px 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: box-shadow 0.3s ease;
}

.search-card:hover {
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.search-input {
  width: 200px;
}

.reset-btn {
  margin-left: 10px;
  background-color: #f5f7fa;
  color: #7f8c8d;
  transition: all 0.2s ease;
}

.reset-btn:hover {
  background-color: #eaecee;
  color: #34495e;
}

/* 表格卡片 */
.table-card {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: box-shadow 0.3s ease;
}

.table-card:hover {
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
}

.table-actions {
  margin-bottom: 15px;
  display: flex;
  justify-content: flex-end;
}

.batch-delete-btn {
  transition: all 0.2s ease;
}

.batch-delete-btn:hover {
  transform: translateY(-2px);
}

.batch-delete-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.main-table {
  width: 100%;
  border-radius: 4px;
  overflow: hidden;
}

.main-table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #2c3e50;
}

.main-table .cell-content {
  transition: color 0.2s ease;
}

.main-table tr:hover .cell-content {
  color: #42b983;
}

.status-tag {
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 0.85rem;
}

.operation-buttons {
  display: flex;
  gap: 5px;
}

.edit-btn {
  color: #3498db;
  transition: all 0.2s ease;
}

.edit-btn:hover {
  color: #2980b9;
  transform: translateY(-2px);
}

.delete-btn {
  color: #e74c3c;
  transition: all 0.2s ease;
}

.delete-btn:hover {
  color: #c0392b;
  transform: translateY(-2px);
}

/* 分页 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 弹窗样式 */
.dialog-form {
  margin-top: 10px;
}

.el-dialog__header {
  border-bottom: 1px solid #eee;
  padding: 15px 20px;
}

.el-dialog__title {
  font-size: 1.1rem;
  font-weight: 600;
  color: #2c3e50;
}

.el-dialog__body {
  padding: 20px;
}

.el-dialog__footer {
  border-top: 1px solid #eee;
  padding: 15px 20px;
}

/* 动画效果 */
.el-button {
  transition: all 0.2s ease;
}

.el-button:hover {
  transform: translateY(-2px);
}

.el-input:focus-within .el-input__wrapper {
  box-shadow: 0 0 0 2px rgba(66, 185, 131, 0.2);
  border-color: #42b983;
}

.el-select:focus-within .el-select__wrapper {
  box-shadow: 0 0 0 2px rgba(66, 185, 131, 0.2);
  border-color: #42b983;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .sidebar {
    width: 60px;
  }

  .nav-item span {
    display: none;
  }

  .nav-item {
    justify-content: center;
    padding: 15px 0;
  }

  .search-form {
    flex-direction: column;
    align-items: flex-start;
  }

  .search-input {
    width: 100%;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>
